<template>
  <el-container>
    <el-dialog
      v-model="dialogVisible"
      title="新增操作"
      width="30%"
      center
      draggable
    >
      <el-form
        :model="form"
        class="addform"
        label-width="auto"
        :rules="addrules"
        ref="ruleFormRef"
      >
        <el-form-item label="用户名:" prop="uid">
          <el-select
            v-model="form.uid"
            placeholder="选择用户名"
            style="width: 100%"
          >
            <el-option
              v-for="item in userlist"
              :key="item.uid"
              :label="item.uname"
              :value="item.uid"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="工作人员名:" prop="sid">
          <el-select
            v-model="form.sid"
            placeholder="选择工作人员名"
            style="width: 100%"
          >
            <el-option
              v-for="item in stafflist"
              :key="item.sid"
              :label="item.sname"
              :value="item.sid"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="矿泉水名称:" prop="wid">
          <el-select
            v-model="form.wid"
            placeholder="选择矿泉水名"
            style="width: 100%"
          >
            <el-option
              v-for="item in waterlist"
              :key="item.wid"
              :label="item.wname"
              :value="item.wid"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="送达状态:" prop="status">
          <el-select
            v-model="form.status"
            placeholder="选择状态"
            style="width: 100%"
          >
            <el-option
              v-for="item in status"
              :key="item"
              :label="item"
              :value="item"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="送达时间:" prop="time">
          <el-date-picker
            v-model="form.time"
            type="datetime"
            placeholder="请挑选时间和日期"
          >
          </el-date-picker>
        </el-form-item>

        <el-form-item label="矿泉水数量:" prop="number">
          <el-input v-model.number="form.number" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item label="空桶数量:" prop="bottle">
          <el-input v-model.number="form.bottle" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmadd(form)">确认</el-button>
        </span>
      </template>
    </el-dialog>

    <el-dialog
      v-model="editVisible"
      title="编辑操作"
      width="30%"
      center
      draggable
    >
      <el-form
        :model="editform"
        class="addform"
        label-width="auto"
        :rules="addrules"
        ref="editFormRef"
      >
        <el-form-item label="送达状态:" prop="status">
          <el-select
            v-model="editform.status"
            placeholder="选择状态"
            style="width: 100%"
          >
            <el-option
              v-for="item in status"
              :key="item"
              :label="item"
              :value="item"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="矿泉水名称:" prop="wid">
          <el-select
            v-model="editform.wid"
            placeholder="选择矿泉水名"
            style="width: 100%"
          >
            <el-option
              v-for="item in waterlist"
              :key="item.wid"
              :label="item.wname"
              :value="item.wid"
            >
            </el-option>
          </el-select>
        </el-form-item>

        
        <el-form-item label="送达时间:" prop="time">
          <el-date-picker
            v-model="editform.time"
            type="datetime"
            placeholder="请挑选时间和日期"
          >
          </el-date-picker>
        </el-form-item>

        <el-form-item label="矿泉水数量:" prop="number">
          <el-input
            v-model.number="editform.number"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="空桶数量:" prop="bottle">
          <el-input
            v-model.number="editform.bottle"
            autocomplete="off"
          ></el-input>
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmedit(editform)"
            >确认</el-button
          >
        </span>
      </template>
    </el-dialog>

    <el-header class="head">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-input v-model="input1" placeholder="请输入订单号或者状态">
            <template #prefix>
              <el-icon class="el-input__icon"><search /></el-icon>
            </template>
          </el-input>
        </el-col>
        <el-col :span="1"></el-col>
        <el-col :span="2">
          <el-button type="primary" @click="select(input1)">查询</el-button>
        </el-col>
        <el-col :span="2">
          <el-button type="success" @click="dialogVisible = true"
            >新增</el-button
          >
        </el-col>
        <el-col :span="2">
          <el-popconfirm
            confirm-button-text="Yes"
            cancel-button-text="No"
            :icon="InfoFilled"
            icon-color="red"
            title="你真的要确认批量删除消息么"
            @confirm="alldelete(multipleSelection)"
          >
            <template #reference>
              <el-button type="danger">批量删除</el-button>
            </template>
          </el-popconfirm>
        </el-col>
        <el-col :span="8"></el-col>
        <el-col :span="3"><span>送水订单表</span></el-col>
      </el-row>
    </el-header>

    <el-main class="table-box">
      <el-table
        :data="tableData"
        :header-cell-style="{ 'text-align': 'center' }"
        :cell-style="{ 'text-align': 'center' }"
        @selection-change="changemult"
        :row-class-name="tableRowClassName"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column
          prop="oid"
          width="150"
          :index="indexMethod"
          label="订单号"
        />
        <el-table-column prop="wname" label="矿泉水名称" width="120">
        </el-table-column>
        <el-table-column prop="number" label="矿泉水数量" width="80">
        </el-table-column>
        <el-table-column prop="bottle" label="回收空桶数量" width="80">
        </el-table-column>
        <el-table-column prop="price" label="单价" width="120">
        </el-table-column>
        <el-table-column prop="total" label="总价" width="120">
        </el-table-column>
        <el-table-column prop="time" label="时间" width="200">
        </el-table-column>
        <el-table-column prop="status" label="状态" width="80">
        </el-table-column>

        <el-table-column label="单项操作">
          <template #default="scope">
            <el-button size="small" @click="handleEdit(scope.$index, scope.row)"
              >编辑</el-button
            >
            <el-popconfirm
              confirm-button-text="Yes"
              cancel-button-text="No"
              :icon="InfoFilled"
              icon-color="red"
              title="你确定要删除该行消息么"
              @confirm="handleDelete(scope.$index, scope.row)"
              
            >
              <template #reference>
                <el-button size="small" type="danger">删除</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
    </el-main>
    <div class="pagin">
      <el-pagination
        layout="prev, pager, next"
        :total="totalNumber"
        :page-size="Pagesize"
        :pager-count="10"
        :current-page="currentPage"
        @current-change="handleCurrentChange"
      ></el-pagination>
    </div>
  </el-container>
</template>

<script>
import { defineComponent, onMounted, reactive, ref } from "vue";
import {
  getuser,
  getstaff,
  getwater,
  getorder,
  getorderdata,
  updateorderbyid,
  saveorder,
  deleteorderbyid,
} from "@/apis/orderData.js";
import { Search } from "@element-plus/icons-vue";
import { ElMessage } from "element-plus";

export default defineComponent({
  components: {
    Search,
  },
  data() {
    return {
      status: ["已送达", "未送达"],
    };
  },

  setup() {
    let multipleSelection = ref("");
    const input1 = ref("");
    const dialogVisible = ref(false);

    let totalNumber = ref(0);
    let currentPage = ref(1);
    let Pagesize = ref(6);

    let editVisible = ref(false);

    let listdata = ref("");
    let tableData = ref("");

    const userlist = ref("");
    const stafflist = ref("");
    const waterlist = ref([]);

    const form = reactive({
      oid: "",
      uid: "",
      sid: "",
      wid: "",
      number: "",
      time: "",
      status: "",
      total: "",
      bottle: "",
    });

    const editform = reactive({
      oid: "",
      uid: "",
      sid: "",
      wid: "",
      number: "",
      time: "",
      status: "",
      total: "",
      price:"",
      bottle: "",
    });

    const postform = {
      oid: "",
      uid: "",
      sid: "",
      wid: "",
      number: "",
      time: "",
      status: "",
      total: "",
      price:"",
      bottle: "",
    };

    const addrules = reactive({
      uid: [
        {
          required: true,
          message: "请输入用户名",
          trigger: "blur",
        },
      ],
      sid: [
        {
          required: true,
          message: "请输入工作人员名字",
          trigger: "blur",
        },
      ],
      wid: [
        {
          required: true,
          message: "请输入矿泉水名称",
          trigger: "blur",
        },
      ],
      status: [
        {
          required: true,
          message: "请选择送达状态",
          trigger: "blur",
        },
      ],
      time: [
        {
          required: true,
          message: "请选择时间",
          trigger: "blur",
        },
      ],
      number: [
        {
          required: true,
          message: "请输入矿泉水数量",
          trigger: "blur",
        },
        { type: "number", message: "类型必须为数字" },
      ],
      bottle: [
        {
          required: true,
          message: "请输入空桶数量",
          trigger: "blur",
        },
        { type: "number", message: "类型必须为数字" },
      ],
    });

function tableRowClassName(row) {
  if (row.row.status == "未送达") {
    return 'warning-row';
  }else if(row.row.status == "已送达"){
    return 'success-row'
  }
   return '';
}

    onMounted(async () => {
      getuserlist();
      getstafflist();
      getwaterlist();
    });

    function mergearray(arr1, arr2) {
      const arrs = arr1.map((item) => {
        const data = arr2.find((i) => item.wid == i.wid);
        return {
          ...item,
          ...data,
          products: data ? data.products : [],
        };
      });
      return arrs;
    }

    function getdata() {
      let page = currentPage.value;
      let size = Pagesize.value;
      getorder().then((res) => {
        listdata.value = res.data.page.list;
        listdata.value = mergearray(listdata.value, waterlist.value);
        totalNumber.value = res.data.page.list.length;
        tableData.value = listdata.value.slice(page * size - size, page * size);
      });
    }

    function getuserlist() {
      let nowtime=Date.now();
      let beforetime=localStorage.getItem("usertime");
      if(beforetime){
        let trust=compareStorage(nowtime,beforetime,"userlist");
        if(trust!=null){
          userlist.value=JSON.parse(trust);
          return;
        }
      }
      
      getuser().then((res) => {
        userlist.value = res.data.page.list;
        localStorage.setItem("usertime",nowtime);
        localStorage.setItem("userlist",JSON.stringify(res.data.page.list));
      });
    }

    function getstafflist() {
      let nowtime=Date.now();
      let beforetime=localStorage.getItem("stafftime");
      if(beforetime){
        let trust=compareStorage(nowtime,beforetime,"stafflist");
        if(trust!=null){
          stafflist.value=JSON.parse(trust);
          return;
        }
      }
      getstaff().then((res) => {
        stafflist.value = res.data.page.list;
        localStorage.setItem("stafftime",nowtime);
        localStorage.setItem("stafflist",JSON.stringify(res.data.page.list));
      });
    }

    async function getwaterlist() {

      let nowtime=Date.now();
      let beforetime=localStorage.getItem("watertime");
      if(beforetime){
        let trust=compareStorage(nowtime,beforetime,"waterlist");
        if(trust!=null){
          waterlist.value=JSON.parse(trust);
          getdata();
          return;
        }
      }
      await getwater().then((res) => {
        waterlist.value = res.data.page.list;
        localStorage.setItem("watertime",nowtime);
        localStorage.setItem("waterlist",JSON.stringify(res.data.page.list));
      });
      getdata();
    }

    function select(prop) {
      let name = { key: prop };
      getorderdata(name).then((res) => {
        listdata.value = res.data.page.list;
        listdata.value = mergearray(listdata.value, waterlist.value);
        totalNumber.value = res.data.page.list.length;
        currentPage.value = 1;
        tableData.value = listdata.value.slice(0, Pagesize.value);
      });
    }

    function handleEdit(index, row) {
      editVisible.value = true;
      editform.oid = row.oid;
      editform.wid = row.wid;
      editform.time = new Date(row.time);
      editform.price = row.price;
      editform.status = row.status;
      editform.number = row.number;
      editform.bottle = row.bottle;
    }

    function getoid(time, uid, sid, wid, number) {
      let year = time.getFullYear();
      let month =
        time.getMonth() < 10
          ? "0" + (time.getMonth() + 1)
          : time.getMonth() + 1;
      let date = time.getDate() < 10 ? "0" + time.getDate() : time.getDate();
      let oid = [year, month, date, uid, sid, wid, number].join("");
      return oid;
    }

    function selectprice(id) {
      let selectedItem = {};
      selectedItem = waterlist.value.find((item) => {
        return item.wid === id;
      });
      return selectedItem.price;
      
    }



    function confirmadd(form) {
      this.$refs.ruleFormRef.validate((valid) => {
        if (valid) {
          form.oid = getoid(
            form.time,
            form.uid,
            form.sid,
            form.wid,
            form.number
          );
          form.total = selectprice(form.wid) * form.number;
          form.time=form.time.getTime();

          saveorder(form)
            .then((res) => {
              if (res.data.code == 0) {
                ElMessage({
                  message: "新增成功",
                  type: "success",
                });

                getdata();
              }
            })
            .catch(function (err) {
              ElMessage({
                message: "表单已存在,错误原因:" + err,
                type: "error",
              });
            });
          dialogVisible.value = false;
        } else {
          ElMessage({
            message: "输入表单不符合规则",
            type: "error",
          });
        }
      });
    }

    function confirmedit(form) {
      this.$refs.editFormRef.validate((valid) => {
        if (valid) {
          postform.oid=form.oid;
          postform.wid=form.wid;
          postform.total=selectprice(form.wid)*form.number;
          postform.time=form.time.getTime();
          postform.status=form.status;
          postform.number=form.number;
          postform.bottle=form.bottle;
          
          updateorderbyid(postform).then((res) => {
            if (res.data.code == 0) {
              ElMessage({
                message: "编辑成功",
                type: "success",
              });
              getdata();
            } else {
              ElMessage({
                message: "编辑失败",
                type: "error",
              });
            }
          });
          editVisible.value = false;
        } else {
          ElMessage({
            message: "编辑表单不符合规则",
            type: "error",
          });
        }
      });
    }

    function alldelete(data) {
      window.console.log(data);
      if (data.length == 0) {
        ElMessage({
          message: "你好像没有选中删除的数据项",
          type: "warning",
        });
      } else {
        deleteorderbyid(data).then((res) => {
          if (res.data.code == 0) {
            ElMessage({
              message: "删除成功",
              type: "success",
            });
            getdata();
          } else {
            ElMessage({
              message: "删除失败",
              type: "error",
            });
          }
        });
      }
    }

    function handleDelete(index, row) {
      //删除操作
      let key = [row.phid];

      deleteorderbyid(key).then((res) => {
        if (res.data.code == 0) {
          ElMessage({
            message: "删除成功",
            type: "success",
          });
          getdata();
        } else {
          ElMessage({
            message: "删除失败",
            type: "error",
          });
        }
      });
    }

    function handleCurrentChange(page) {
      currentPage.value = page;
      let size = Pagesize.value;
      tableData.value = listdata.value.slice(page * size - size, page * size);
    }

    function indexMethod(index) {
      return index + 1 + (currentPage.value - 1) * Pagesize.value;
    }

    function changemult(val) {
      let ids = [];
      for (let i in val) {
        ids.push(val[i].oid);
      }
      multipleSelection.value = ids;
    }

    function compareStorage(newtime,oldtime,Storagename){
      if(newtime-oldtime<8640000){
        let data=localStorage.getItem(Storagename);
        return data;                  
      }else{
        localStorage.removeItem(Storagename);
      }
      return null;
    }



    return {
      input1,
      tableData,
      multipleSelection,
      userlist,
      stafflist,
      waterlist,
      dialogVisible,
      editVisible,
      select,
      addrules,
      confirmadd,
      indexMethod,
      editform,
      totalNumber,
      currentPage,
      Pagesize,
      handleEdit,
      handleDelete,
      confirmedit,
      alldelete,
      form,
      tableRowClassName,
      changemult,
      handleCurrentChange,
    };
  },
});
</script>
<style scoped>
.head {
  font-size: 18px;
}

.dialog-footer button:first-child {
  margin-right: 10px;
}
.addform >>> .el-form-item {
  padding-left: 8%;
}
.addform >>> .el-input {
  width: 80%;
}
.pagin {
  text-align: center;
  margin-left: -10%;
}

.el-table >>> .warning-row{
  --el-table-tr-bg-color:#f8e3c5;
}

.el-table >>> .success-row{
  --el-table-tr-bg-color:#e1f3d8; 
}

</style>